package com.example.hhh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hhh.model.pojo.Business;
import com.example.hhh.service.BusinessService;
import com.example.hhh.mapper.BusinessMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.example.hhh.service.WorkorderService;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/api/business")
@CrossOrigin(origins = "*")
public class BusinessController {
    @Autowired
    private BusinessService businessService;
    
    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private WorkorderService workorderService;

    /**
     * Excel批量导入业务数据
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importBusinesses(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择文件");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 校验Excel表头
            List<String> expectedHeaders = List.of("业务名称", "业务类型", "描述", "标准价格", "成本", "预计完成时间(小时)", "状态", "创建时间", "更新时间");
            List<String> actualHeaders = readExcelHeaders(file);
            
            if (!actualHeaders.equals(expectedHeaders)) {
                result.put("success", false);
                result.put("message", "Excel模板不正确！请使用业务导入模板，表头必须包含：" + String.join(", ", expectedHeaders));
                return ResponseEntity.badRequest().body(result);
            }
            
            List<Business> businesses = readExcelFile(file);
            int successCount = 0;
            List<String> errors = new ArrayList<>();
            
            for (int i = 0; i < businesses.size(); i++) {
                try {
                    Business business = businesses.get(i);
                    
                    // 验证必填字段
                    if (business.getBusinessName() == null || business.getBusinessName().trim().isEmpty()) {
                        errors.add("第" + (i + 2) + "行：业务名称不能为空");
                        continue;
                    }
                    
                    // 检查业务名称是否重复
                    QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("business_name", business.getBusinessName().trim());
                    Business existingBusiness = businessService.getOne(queryWrapper);
                    if (existingBusiness != null) {
                        errors.add("第" + (i + 2) + "行：业务名称'" + business.getBusinessName().trim() + "'已存在，跳过导入");
                        continue;
                    }
                    
                    // 设置时间字段
                    business.setCreateTime(new Date());
                    business.setUpdateTime(new Date());
                    
                    // 检查插入结果
                    int insertResult = businessMapper.insert(business);
                    if (insertResult > 0) {
                        successCount++;
                    } else {
                        errors.add("第" + (i + 2) + "行：数据库插入失败");
                    }
                } catch (Exception e) {
                    errors.add("第" + (i + 2) + "行导入失败：" + e.getMessage());
                    e.printStackTrace(); // 打印详细错误信息到控制台
                }
            }
            
            result.put("success", successCount > 0 || errors.isEmpty()); // 只有真正有成功插入或没有错误才算成功
            result.put("successCount", successCount);
            result.put("errorCount", errors.size());
            result.put("errors", errors);
            result.put("message", "导入完成，成功" + successCount + "条，失败" + errors.size() + "条");
            result.put("totalProcessed", businesses.size()); // 添加处理总数信息
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入失败：" + e.getMessage());
            java.io.StringWriter sw = new java.io.StringWriter();
            e.printStackTrace(new java.io.PrintWriter(sw));
            result.put("stackTrace", sw.toString());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 读取Excel表头
     */
    private List<String> readExcelHeaders(MultipartFile file) throws IOException {
        List<String> headers = new ArrayList<>();
        
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            Row headerRow = sheet.getRow(0);
            
            if (headerRow != null) {
                for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                    Cell cell = headerRow.getCell(i);
                    if (cell != null) {
                        headers.add(cell.toString().trim());
                    } else {
                        headers.add("");
                    }
                }
            }
        }
        
        return headers;
    }
    
    /**
     * 读取Excel文件
     */
    private List<Business> readExcelFile(MultipartFile file) throws IOException {
        List<Business> businesses = new ArrayList<>();
        
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                
                Business business = new Business();
                
                // 业务名称
                Cell nameCell = row.getCell(0);
                if (nameCell != null && !nameCell.toString().trim().isEmpty()) {
                    business.setBusinessName(nameCell.toString().trim());
                } else {
                    continue; // 跳过空行
                }
                
                // 业务类型
                Cell typeCell = row.getCell(1);
                if (typeCell != null) {
                    business.setBusinessType(typeCell.toString().trim());
                }
                
                // 描述
                Cell descCell = row.getCell(2);
                if (descCell != null) {
                    business.setDescription(descCell.toString().trim());
                }
                
                // 标准价格
                Cell priceCell = row.getCell(3);
                if (priceCell != null) {
                    try {
                        business.setStandardPrice(new BigDecimal(priceCell.toString()));
                    } catch (Exception e) {
                        business.setStandardPrice(BigDecimal.ZERO);
                    }
                }
                
                // 成本
                Cell costCell = row.getCell(4);
                if (costCell != null) {
                    try {
                        business.setCost(new BigDecimal(costCell.toString()));
                    } catch (Exception e) {
                        business.setCost(BigDecimal.ZERO);
                    }
                }
                
                // 预计完成时间
                Cell durationCell = row.getCell(5);
                if (durationCell != null) {
                    try {
                        business.setDuration((int) durationCell.getNumericCellValue());
                    } catch (Exception e) {
                        business.setDuration(1);
                    }
                }
                
                // 状态
                Cell statusCell = row.getCell(6);
                if (statusCell != null) {
                    try {
                        business.setStatus((int) statusCell.getNumericCellValue());
                    } catch (Exception e) {
                        business.setStatus(1); // 默认可用
                    }
                } else {
                    business.setStatus(1);
                }
                
                // 设置时间字段
                business.setCreateTime(new Date());
                business.setUpdateTime(new Date());
                
                businesses.add(business);
            }
        }
        
        return businesses;
    }

    /**
     * 导出业务数据到Excel
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportBusinesses() {
        try {
            List<Business> businesses = businessService.list();
            
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("业务信息");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] excelHeaders = {"业务名称", "业务类型", "描述", "标准价格", "成本", "预计完成时间(小时)", "状态", "创建时间", "更新时间"};
            for (int i = 0; i < excelHeaders.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(excelHeaders[i]);
            }
            
            // 填充数据
            for (int i = 0; i < businesses.size(); i++) {
                Business business = businesses.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(business.getBusinessName() != null ? business.getBusinessName() : "");
                row.createCell(1).setCellValue(business.getBusinessType() != null ? business.getBusinessType() : "");
                row.createCell(2).setCellValue(business.getDescription() != null ? business.getDescription() : "");
                row.createCell(3).setCellValue(business.getStandardPrice() != null ? business.getStandardPrice().doubleValue() : 0.0);
                row.createCell(4).setCellValue(business.getCost() != null ? business.getCost().doubleValue() : 0.0);
                row.createCell(5).setCellValue(business.getDuration() != null ? business.getDuration() : 1);
                row.createCell(6).setCellValue(business.getStatus() != null ? business.getStatus() : 1);
                row.createCell(7).setCellValue(business.getCreateTime() != null ? business.getCreateTime().toString() : "");
                row.createCell(8).setCellValue(business.getUpdateTime() != null ? business.getUpdateTime().toString() : "");
            }
            
            // 自动调整列宽
            for (int i = 0; i < excelHeaders.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            byte[] bytes = outputStream.toByteArray();
            
            // 保存文件到指定目录
            String exportDir = "C:\\Users\\20642\\Desktop\\daochu";
            File dir = new File(exportDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            String fileName = "业务信息_" + System.currentTimeMillis() + ".xlsx";
            String filePath = exportDir + "\\" + fileName;
            File file = new File(filePath);
            
            try (FileOutputStream fileOut = new FileOutputStream(file)) {
                fileOut.write(bytes);
            }
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
            
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 新增
    @PostMapping
    public ResponseEntity<Map<String, Object>> addBusiness(@RequestBody Business business) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证必填字段
            if (business.getBusinessName() == null || business.getBusinessName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "业务名称不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查业务名称是否重复
            QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("business_name", business.getBusinessName().trim());
            Business existingBusiness = businessService.getOne(queryWrapper);
            if (existingBusiness != null) {
                result.put("success", false);
                result.put("message", "业务名称'" + business.getBusinessName().trim() + "'已存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            business.setCreateTime(new Date());
            business.setUpdateTime(new Date());
            
            boolean success = businessService.save(business);
            result.put("success", success);
            result.put("message", success ? "业务添加成功" : "业务添加失败");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加业务失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    // 删除
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteBusiness(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查是否有关联工单
            QueryWrapper<com.example.hhh.model.pojo.Workorder> workorderQuery = new QueryWrapper<>();
            workorderQuery.eq("business_id", id);
            long count = workorderService.count(workorderQuery);
            if (count > 0) {
                result.put("success", false);
                result.put("message", "该业务下存在工单，无法删除！");
                return ResponseEntity.ok(result);
            }
            boolean success = businessService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败，数据不存在或有关联数据");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    // 修改
    @PutMapping
    public boolean updateBusiness(@RequestBody Business business) {
        business.setUpdateTime(new Date());
        return businessService.updateById(business);
    }

    // 查询单个
    @GetMapping("/{id}")
    public Business getBusiness(@PathVariable Integer id) {
        return businessService.getById(id);
    }

    // 查询所有
    @GetMapping("/list")
    public Map<String, Object> getAllBusiness(@RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "12") Integer limit,
                                              @RequestParam(required = false) String search) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
            if (search != null && !search.trim().isEmpty()) {
                queryWrapper.like("business_name", search.trim())
                           .or()
                           .like("business_type", search.trim())
                           .or()
                           .like("description", search.trim());
            }
            
            Page<Business> pageParam = new Page<>(page, limit);
            IPage<Business> pageResult = businessService.page(pageParam, queryWrapper);
            
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("pages", pageResult.getPages());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            
        } catch (Exception e) {
            result.put("records", new ArrayList<>());
            result.put("total", 0);
            result.put("pages", 0);
            result.put("current", page);
            result.put("size", limit);
        }
        
        return result;
    }

    // 分页查询
    @GetMapping("/page")
    public IPage<Business> getBusinessPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Business> page = new Page<>(pageNum, pageSize);
        return businessService.page(page, new QueryWrapper<>());
    }
}